package com.applozic.mobicomkit.uiwidgets.attachmentview;

import android.media.MediaRecorder;
import android.support.v4.app.FragmentActivity;

import com.applozic.mobicomkit.uiwidgets.conversation.ConversationUIService;
import com.applozic.mobicommons.commons.core.utils.Utils;

import java.io.File;

/**
 * Created by Rahul-PC on 17-07-2017.
 */

public class ApplozicAudioRecordManager implements MediaRecorder.OnInfoListener, MediaRecorder.OnErrorListener {

    FragmentActivity context;
    String audioFileName, timeStamp;
    ConversationUIService conversationUIService;
    private AudioRecordFunc audioRecorder = AudioRecordFunc.getInstance();

    private String outputFile = null;
    private long startTime;
    private long endTime;


    public ApplozicAudioRecordManager(FragmentActivity context) {
        this.conversationUIService = new ConversationUIService(context);
        this.context = context;
    }

    public void setOutputFile(String outputFile) {
        this.outputFile = outputFile;
        if (audioRecorder != null) {
            audioRecorder.setAudioFilePath(outputFile);
        }
    }

    public void setAudioFileName(String audioFileName) {
        this.audioFileName = audioFileName;
    }

    public void setTimeStamp(String timeStamp) {
        this.timeStamp = timeStamp;
    }

    public void recordAudio() {
        if (audioRecorder != null) {
            audioRecorder.startRecordAndFile();
        }
        startTime = System.currentTimeMillis();
    }

    public void cancelAudio() {

        audioRecorder.stopRecordAndFile();
        if (outputFile != null) {
            File file = new File(outputFile);
            if (file != null && file.exists()) {
                Utils.printLog(context, "AudioFRG:", "File deleted...");
                file.delete();
            }
        }

    }

    public void sendAudio() {
        audioRecorder.stopRecordAndFile();
        endTime = System.currentTimeMillis();


        //FILE CHECK ....

        if (outputFile != null) {
            if (!(new File(outputFile).exists())) {
//                Toast.makeText(context, R.string.tap_on_mic_button_to_record_audio, Toast.LENGTH_SHORT).show();
                //cancel the record action
                return;
            }
            long audioTime = endTime - startTime;
            conversationUIService.sendAudioMessage(outputFile, audioTime);
        }

    }


    @Override
    public void onInfo(MediaRecorder mr, int what, int extra) {

    }

    @Override
    public void onError(MediaRecorder mr, int what, int extra) {

    }
}